package com.labManage.shiro;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.issueRedirect(	request, response, getSuccessUrl(),null,true);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //1 先进行验证码的校验
        //从session中获取正确的验证码
        HttpServletRequest httpRequest=(HttpServletRequest)request;
		HttpSession session=httpRequest.getSession();
        //从session中取出正确的验证码
        String validateCode=(String) session.getAttribute("verificationCode");
        //取出页面输入的验证码
        String realmCode=httpRequest.getParameter("verificationCode");
        if(validateCode!=null && realmCode!=null && !validateCode.equals(realmCode)){
            //2 验证码认证失败 讲验证码错误信息保存到request中的 shiroLoginFailure 属性中
            httpRequest.setAttribute("shiroLoginFailure", "verificationCodeErr");
            //拒绝访问 ，不在验证账号和密码
            return true;
        }
        //3 验证码认证成功 就进行用户名和密码的认证
        return super.onAccessDenied(request, response);
    }
}
